import { createStore } from 'vuex'
import axios  from 'axios'
import { ElMessage } from 'element-plus'


export default createStore({
  state: {
    userInfo:{
      username:''
    },
    buyInfo:{}
  },
  getters: {
  },
  mutations: {
    //退出
    exit(){
      sessionStorage.clear()
    },
    //登录
    login(state,data){
      state.userInfo.username = data
      sessionStorage.token = data
    },
    //暂存buyInfo
    buyInfo(state,data){
      state.buyInfo = data
    }
  },
  actions: {
    //登录
    login(context,data){
      return new Promise((resolve,reject)=>{
        axios.get('http://localhost:3000/userlist').then(res=>{
          let flag=  res.data.find(item=>item.username==data.username&&item.password==data.password)
          if(flag!=undefined){
            context.commit('login',data.username)
            resolve()
          }else{
            ElMessage({
              showClose: true,
              message: '账号或密码错误',
              center: true,
            })
          }
        })
      }) 
    },
    //退出
    exit(context){
      context.commit('exit')
    }
  },
  modules: {
  }
})
